import { Modal } from "@arco-design/web-vue";
import { FunctionalComponent } from "vue";
import { FormMethods } from "../GuatForm/types";
import { get } from "lodash-es";

type Props = Omit<InstanceType<typeof Modal>["$props"], "visible"> & {
  validateBeforeOk?: FormMethods["validate"];
  validateFormCallback?: (validatePassed: boolean) => {};
};
type UseModalReturn = [
  FunctionalComponent<Props>,
  {
    setModalVisible: (visible: boolean) => void;
  }
];

export default function useModal(): UseModalReturn {
  const modalVisible = ref(false);

  const setModalVisible = (visible: boolean) => {
    modalVisible.value = visible;
  };

  const CustomModal: FunctionalComponent<Props> = (props, { slots }) => {
    const internalProps: Partial<Props> = {
      width: 720,
      titleAlign: "start",
      mask: true,
      draggable: true,
      unmountOnClose: true,
    };
    const _props = {
      ...internalProps,
      ...props,
    };

    async function validateFormBeforeOk() {
      const validate = props.validateBeforeOk ?? get(props, "validate-before-ok") ?? undefined;
      if (!validate) return true;
      if (await validate()) {
        props.validateFormCallback?.(false);
        return false;
      } else {
        props.validateFormCallback?.(true);
        return true;
      }
    }

    return (
      <Modal
        visible={modalVisible.value}
        onUpdate:visible={(value) => (modalVisible.value = value)}
        onBeforeOk={validateFormBeforeOk}
        {..._props}
      >
        {slots.default?.()}
      </Modal>
    );
  };

  return [CustomModal, { setModalVisible }];
}
